package admin_user_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"blog_go/plugins/email"
	"blog_go/utils"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type BindEmailReq struct {
	Email    string  `json:"email" binding:"required,email" msg:"邮箱非法"`
	Code     *string `json:"code"`
	Password string  `json:"password" binding:"required" msg:"请输入密码"`
}

func (AdminUserApi) UserBindEmail(c *gin.Context) {
	var req BindEmailReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error(err)
		panic(res.ErrorMsg{Err: err, Data: &req})
	}
	// 先校验密码
	_claims, _ := c.Get(utils.Claims)
	claims := _claims.(*utils.CustomClaims)
	var userModel models.UserModel
	err := global.DB.Take(&userModel, claims.UserID).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	if !utils.ComparePwd(userModel.Password, req.Password) {
		panic("用户密码不正确")
	}
	session := sessions.Default(c)
	// 第一次发送验证码
	if req.Code == nil {
		code := utils.RandomCode(4)
		newCodeApi := email.NewCode()
		err := newCodeApi.Send(req.Email, "你好你的code是: "+code)
		if err != nil {
			logrus.Error(err)
			panic(err)
		}
		session.Set("code", code)
		// 在这里修改,1800表示有效时间为1800秒
		session.Options(sessions.Options{MaxAge: 1800})
		err = session.Save()
		if err != nil {
			logrus.Error(err)
			panic(err)
		}
		res.OkWithMessage("验证码已发送", c)
		return
	}
	// 当传来了code的时候
	getCode := session.Get("code")
	if getCode != *req.Code {
		panic("验证码错误")
	}
	// 绑定邮箱
	err = global.DB.Model(&userModel).Update("email", req.Email).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	// fix 有问题
	session.Delete("code")
	res.OkWithMessage("绑定成功", c)
}
